from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from apps.backend import models
from rest_framework.exceptions import ValidationError
from django.contrib.auth.hashers import check_password
from apps.backend.login.serializers import LoginSerializer
from drf_template_admin.enums import config
from drf_template_admin.services.JwtService import JWT
from drf_template_admin.services.RedisService import redis_connection
from drf_template_admin.enums import expire
import random, json
from drf_template_admin.services.Throttles import VerifyCodeThrottle
from drf_template_admin.services.AuthClientID import ClientIDAuthentication

class CaptchaView(APIView):
    authentication_classes = [ClientIDAuthentication]
    throttle_classes = [VerifyCodeThrottle,]
    def get(self, request, *args, **kwargs):
        ip = request.META.get('HTTP_CLIENT_ID')
        code = ''.join(random.choices(config.CAPTCHA, k = 4))

        redisConnection = redis_connection('verify_code')
        redisConnection.set_redis(ip, code, expire.VERIFY_CODE)
        
        return Response({'status': status.HTTP_200_OK, "data": code, 'message': 'success'})

class LoginView(APIView): 
    authentication_classes = [ClientIDAuthentication]
    def post(self, request, *args, **kwargs):
        ser = LoginSerializer(data=request.data)
        if not ser.is_valid():
            raise ValidationError({"status": status.HTTP_428_PRECONDITION_REQUIRED, "errorCode": "20001", "errorMessage": ser.errors})

        redisConnection = redis_connection('verify_code')
        verify_code = redisConnection.get_redis(request.auth)
        if not verify_code:
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "20002", "errorMessage": "验证码已过期"})
        
        if verify_code.lower() != ser.data.get('captcha').lower():
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "20003", "errorMessage": "验证码错误"})
        
        username = ser.data.get('username')
        password = ser.data.get('password')
        user = models.SystemAdmin.objects.filter(username=username).first()
        if not user:
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "20004", "errorMessage": "用户不存在"})
        
        if not check_password(password, user.password):
            raise ValidationError({"status": status.HTTP_400_BAD_REQUEST, "errorCode": "20005", "errorMessage": "密码错误"})
        
        jwt_service = JWT()
        jwt_token = jwt_service.generate_token(user.id, user.username) 


        redisConnection = redis_connection('token')
        _dict = {'id': user.id, 'scope': user.scope, 'role': user.role_id}
        redisConnection.set_redis(jwt_token, json.dumps(_dict), expire.BACKEND_EXPIRE)

        data = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'token': jwt_token,
            # 'redis': json.loads(redisConnection.get_redis(jwt_token))
        }

        return Response({'status': status.HTTP_200_OK, "data":data, 'message': 'success'})
